package gui.visu.listeners;

import gui.visu.dialogs.JDialogColorWheel;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.image.BufferedImage;

import javax.swing.JDialog;

import data.visu.utils.ImageLoader;

/**
 * @author Charles Perin
 * 29 mars 2011
 * LIMSI - INRIA Rennes
 * charles.perin@free.fr
 *
 */
public class ColorWheelListener implements MouseListener {


	private boolean isPressed = false;

	private JDialogColorWheel parent;

	private BufferedImage image;

	private int xCenter, yCenter;

	private JDialog dialogParent;

	private static final int RAYON_OK_BUTTON = 51;
	private static final int RAYON_NOTHING = 74;
	private static final int RAYON_WHEEL = 362;

	public ColorWheelListener(JDialogColorWheel parent, JDialog dialogParent) {
		this.parent=parent;
		this.dialogParent = dialogParent;
		image = ImageLoader.createBufferedImage("colorWheel.png");
	}

	public void setButtonOkDimension(Dimension size) {
		xCenter = (int) (size.getWidth()/2);
		yCenter = (int) (size.getHeight()/2);
	}

	@Override
	public void mouseClicked(MouseEvent e) {
		if(e.getButton()==MouseEvent.BUTTON1){
			if(e.getClickCount()==1){
				processMouseClick(e.getX(), e.getY());
			}
		}
	}

	private void processMouseClick(int x, int y) {
		if(isOkButton(x,y)){
			parent.modifyColor();
			if(dialogParent!=null){
				dialogParent.setEnabled(true);
			}
			else{
				parent.getParent().setEnabled(true);
			}
			parent.dispose();
		}
		else if(isColor(x,y)){
			int c = image.getRGB(x,y);
			int  red = (c & 0x00ff0000) >> 16;
			int  green = (c & 0x0000ff00) >> 8;
			int  blue = c & 0x000000ff;
			parent.setSelectedColor(new Color(red,green,blue));
		}
	}

	private boolean isOkButton(int x, int y) {
		double dist = Math.sqrt((x-xCenter)*(x-xCenter)+(y-yCenter)*(y-yCenter));
		if(dist<RAYON_OK_BUTTON)return true;
		return false;
	}

	private boolean isColor(int x, int y) {
		double dist = Math.sqrt((x-xCenter)*(x-xCenter)+(y-yCenter)*(y-yCenter));
		if(dist<RAYON_WHEEL && dist>RAYON_NOTHING)return true;
		return false;
	}

	@Override
	public void mouseEntered(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mouseExited(MouseEvent arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void mousePressed(MouseEvent e) {
		if(isOkButton(e.getX(), e.getY())){
			isPressed = true;
			parent.okPressed(true);
		}
	}

	@Override
	public void mouseReleased(MouseEvent arg0) {
		if(isPressed){
			parent.okPressed(false);
			isPressed = false;
		}
	}



}
